/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.task.ServiceTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ProcessEngineConfiguration;
import com.je.bpm.engine.delegate.event.ActivitiEventDispatcher;
import com.je.bpm.engine.delegate.event.ActivitiEventType;
import com.je.bpm.engine.delegate.event.impl.ActivitiEventBuilder;
import com.je.bpm.engine.impl.calendar.DurationHelper;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.AbstractJobEntity;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.JobEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 *
 */

public class JobRetryCmd implements Command<Object> {

    private static final Logger log = LoggerFactory.getLogger(JobRetryCmd.class.getName());

    protected String jobId;
    protected Throwable exception;

    public JobRetryCmd(String jobId, Throwable exception) {
        this.jobId = jobId;
        this.exception = exception;
    }

    public Object execute(CommandContext commandContext) {
        JobEntity job = commandContext.getJobEntityManager().findById(jobId);
        if (job == null) {
            return null;
        }

        ProcessEngineConfiguration processEngineConfig = commandContext.getProcessEngineConfiguration();

        ExecutionEntity executionEntity = fetchExecutionEntity(commandContext, job.getExecutionId());
        FlowElement currentFlowElement = executionEntity != null ? executionEntity.getCurrentFlowElement() : null;

        String failedJobRetryTimeCycleValue = null;
        if (currentFlowElement instanceof ServiceTask) {
            failedJobRetryTimeCycleValue = ((ServiceTask) currentFlowElement).getFailedJobRetryTimeCycleValue();
        }

        AbstractJobEntity newJobEntity = null;
        if (currentFlowElement == null || failedJobRetryTimeCycleValue == null) {

            log.debug("activity or FailedJobRetryTimerCycleValue is null in job " + jobId + ". only decrementing retries.");

            if (job.getRetries() <= 1) {
                newJobEntity = commandContext.getJobManager().moveJobToDeadLetterJob(job);
            } else {
                newJobEntity = commandContext.getJobManager().moveJobToTimerJob(job);
            }

            newJobEntity.setRetries(job.getRetries() - 1);
            if (job.getDuedate() == null || JobEntity.JOB_TYPE_MESSAGE.equals(job.getJobType())) {
                // add wait time for failed async job
                newJobEntity.setDuedate(calculateDueDate(commandContext, processEngineConfig.getAsyncFailedJobWaitTime(), null));
            } else {
                // add default wait time for failed job
                newJobEntity.setDuedate(calculateDueDate(commandContext, processEngineConfig.getDefaultFailedJobWaitTime(), job.getDuedate()));
            }
        } else {
            try {
                DurationHelper durationHelper = new DurationHelper(failedJobRetryTimeCycleValue, processEngineConfig.getClock());
                int jobRetries = job.getRetries();
                if (job.getExceptionMessage() == null) {
                    // change default retries to the ones configured
                    jobRetries = durationHelper.getTimes();
                }

                if (jobRetries <= 1) {
                    newJobEntity = commandContext.getJobManager().moveJobToDeadLetterJob(job);
                } else {
                    newJobEntity = commandContext.getJobManager().moveJobToTimerJob(job);
                }

                newJobEntity.setDuedate(durationHelper.getDateAfter());

                if (job.getExceptionMessage() == null) { // is it the first exception
                    log.debug("Applying JobRetryStrategy '" + failedJobRetryTimeCycleValue + "' the first time for job " +
                            job.getId() + " with " + durationHelper.getTimes() + " retries");

                } else {
                    log.debug("Decrementing retries of JobRetryStrategy '" + failedJobRetryTimeCycleValue + "' for job " + job.getId());
                }

                newJobEntity.setRetries(jobRetries - 1);

            } catch (Exception e) {
                throw new ActivitiException("failedJobRetryTimeCylcle has wrong format:" + failedJobRetryTimeCycleValue, exception);
            }
        }

        if (exception != null) {
            newJobEntity.setExceptionMessage(exception.getMessage());
            newJobEntity.setExceptionStacktrace(getExceptionStacktrace());
        }

        // Dispatch both an update and a retry-decrement event
        ActivitiEventDispatcher eventDispatcher = commandContext.getEventDispatcher();
        if (eventDispatcher.isEnabled()) {
            eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, newJobEntity));
            eventDispatcher.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_RETRIES_DECREMENTED, newJobEntity));
        }

        return null;
    }

    protected Date calculateDueDate(CommandContext commandContext, int waitTimeInSeconds, Date oldDate) {
        Calendar newDateCal = new GregorianCalendar();
        if (oldDate != null) {
            newDateCal.setTime(oldDate);

        } else {
            newDateCal.setTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime());
        }

        newDateCal.add(Calendar.SECOND, waitTimeInSeconds);
        return newDateCal.getTime();
    }

    protected String getExceptionStacktrace() {
        StringWriter stringWriter = new StringWriter();
        exception.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }

    protected ExecutionEntity fetchExecutionEntity(CommandContext commandContext, String executionId) {
        if (executionId == null) {
            return null;
        }
        return commandContext.getExecutionEntityManager().findById(executionId);
    }

}
